package com.sample.springbatch.common;

import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class BaseController {


    public void addSessionData(String key, Object value) {
        getSession().setAttribute(key, value);
    }

    public void removeSessionData(String key){
        getSession().removeAttribute(key);
    }

    public Object getSessionData(String key) {
        return getSession().getAttribute(key);
    }

    public HttpSession getSession() {
        HttpSession session = null;
        try {
            session = getHttpRequest().getSession();
        } catch (Exception e) {
        }
        return session;
    }


    public String getParam(String name){
        return getHttpRequest().getParameter(name);
    }

    public String getCookie(String name){
        if(StringUtils.isEmpty(name)){
            return "";
        }
        Cookie[] cookies = getHttpRequest().getCookies();//这样便可以获取一个cookie数组
        if (null==cookies) {
            return "";
        } else {
            for(Cookie cookie : cookies){
                if(name.equals(cookie.getName())){
                    return cookie.getValue();
                }
            }
        }
        return "";
    }

    public void addCookie(String name, String value){
        Cookie cookie = new Cookie(name.trim(), value.trim());
        cookie.setMaxAge(60 * 60);// 设置为30min
        cookie.setPath("/");
        cookie.setDomain(".jiangrongxin.com");
        getHttpResponse().addCookie(cookie);
    }

	HttpServletRequest getHttpRequest(){
		ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		return attr.getRequest();
	}

    HttpServletResponse getHttpResponse(){
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        return  response;
    }
}
